<?php

namespace App\Http\Controllers\Api\V1\Vuls;

use App\Http\Controllers\Api\V1\BaseController;
//use App\Http\Controllers\Api\V1\TransformerController;
//use App\Http\Controllers\Api\V1\Vuls\LevelTransformer;
use App\Models\Vuls\Category;
use App\Models\Vuls\Level;
use App\Http\Controllers\Api\V1\CustomFommat;
use App\Models\Vuls\Vuls;
use App\Models\Vuls\VulsCount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class VulsController extends BaseController
{
    /**
     * getLevelList 获取漏洞等级列表
     * 
     * @return \Dingo\Api\Http\Response
     */
    public function getLevelList(){
        $lists = Level::withoutTrashed()->orderby('created_at','desc')->select('id','name')->get();
        return $this->response->collection($lists, new LevelTransformer, function ($resource, $fractal) {
            $fractal->setSerializer(new CustomFommat());
        });
    }

    /**
     * getVulsCategorys 获取漏洞分类
     *
     * @param Request $request
     * @return mixed
     */
    public function getVulsCategorys(Request $request){
        $id = $request->id ? $request->id : false;
        $lists = Category::getCateNames($id);
        return $this->returnArray($lists);
    }

    /**
     * addVuls 提交漏洞
     * 
     * @param Request $request
     * @return mixed
     */
    public function addVuls(Request $request){
        $data = $request->all();
        $validator = Vuls::validate($request->all());
        if ($validator->fails()) {
            return $this->returnArray([],442,$validator->errors()->first());
        }
        $data['vuls_number'] = VulsCount::creatVulsCode();
        $exis = $this->userExists();
        if(!$exis){
            return $this->returnArray([], 442, '用户信息不存在!');
        }
        $data['user_id'] = $exis;
        $data['app_id'] = 0;
        $data['desciption'] = '';
        $data['content'] = clean($request->contents, 'user_topic_body');
        $data['status'] = 0;
        $fromUrlXss = clean($request->from_url, 'user_topic_body');
        $payload = clean($request->payload, 'user_topic_body');
        $data['form_url'] = $fromUrlXss ? $fromUrlXss : '';
        $data['payload'] = $payload ? $payload : '';
        $returnVuls = Vuls::create($data);
        $date = date('Y');
        $sql = 'insert into vuls_count (year,count) values (?, ?) on duplicate key update count=count+1';
        DB::insert($sql, [$date,1]);
        return $this->returnArray($returnVuls );
    }

    /**
     * getVulsInfo 个人中心->我的漏洞列表
     *
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     */
    public function getVulsInfo(Request $request){
        $exis = $this->userExists();
        if(!$exis){
           return $this->returnArray([], 442, '用户信息不存在!');
        }
        $lists = Vuls::where('user_id', '=', $exis)
            ->select('id', 'title', 'reward', 'credit', 'status', 'created_at', 'level_id', 'vuls_number', 'content')
            ->paginate(10);
        if($request->id){
            $id = $request->id;
            $lists = Vuls::where([['id', $id],['user_id', $exis],])
                ->select('id as vuls_id', 'title as vuls_title', 'reward as vuls_reward', 'credit as vuls_credit', 'status as vuls_status', 'created_at as vuls_created_at', 'level_id as vuls_level', 'vuls_number', 'content as vuls_content')
                ->get();
            return $this->returnArray($lists);
        }
        return $this->response->paginator($lists, new VulsTransformer,[], function ($resource, $fractal) {
            $fractal->setSerializer(new CustomFommat());
        });
    }

    /**
     * getVulsStatus 获取漏洞状态
     *
     * @return mixed
     */
    public function getVulsStatus(){
        $statusList = Vuls::$vulsStatusMerge;
        $transformRes = collect($statusList)->transform(function($item, $key){
            $item = ['id'=>$key,'name'=>$item['name'],'status_code'=>$item['code']];
            return $item;
        })->all();
        return $this->returnArray($transformRes);
    }

    /**
     * searchSelectVuls 个人中心漏洞检索功能
     *
     * @param Request $request
     * @return \Dingo\Api\Http\Response|mixed
     */
    public function searchSelectVuls(Request $request){
        $exis = $this->userExists();
        if(!$exis){
            return $this->returnArray([], 442, '用户信息不存在!');
        }
        $keys = collect(Vuls::$vulsStatus)->keys()->all();
        $status = $request->status != '' ? explode(',', Vuls::$vulsStatusMerge[$request->status]['code']) : $keys;
        $lists = Vuls::where('user_id', '=', $exis)
            ->whereIn('status', $status)
            ->select('id', 'title', 'reward', 'credit', 'status', 'created_at', 'level_id', 'vuls_number', 'content')
            ->paginate(10);
        return $this->response->paginator($lists, new VulsTransformer,[], function ($resource, $fractal) {
            $fractal->setSerializer(new CustomFommat());
        });
    }
    /**
     * userExists 判断用户信息是否存在
     *
     * @return bool|mixed
     */
    private  function userExists(){
        if (!\Auth::user()) {
            return 1;
        }
        return Auth::user()->id;
    }

    /**
     * generateCaptcha 获取验证码
     *
     * @return mixed
     */
    public function generateCaptcha(){
        return $this->returnArray(captcha_img());
    }
}
